//package com.plian.system.service.fr.internalauditmanagement.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.config.YthTaskObserver;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.dto.fr.internalauditmanagement.IamWorkSystemDTO;
//import com.plian.system.dto.fr.internalauditmanagement.IamWorkSystemDetailDTO;
//import com.plian.system.entity.fr.internalauditmanagement.IamWorkSystem;
//import com.plian.system.entity.fr.internalauditmanagement.IamWorkSystemDetail;
//import com.plian.system.entity.sys.Org;
//import com.plian.system.mapper.fr.internalauditmanagement.IamWorkSystemDetailMapper;
//import com.plian.system.mapper.fr.internalauditmanagement.IamWorkSystemMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ListResult;
//import com.plian.system.model.ObjResult;
//import com.plian.system.config.exception.MyRuntimeException;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.search.TokenSearch;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.service.fr.internalauditmanagement.IamWorkSystemDetailService;
//import com.plian.system.service.fr.internalauditmanagement.IamWorkSystemService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.service.yth.ISznbAuditWorkSystemService;
//import com.plian.system.vo.fr.internalauditmanagement.IamWorkSystemDetailVO;
//import com.plian.system.vo.fr.internalauditmanagement.IamWorkSystemVO;
//import com.plian.system.wrapper.fr.internalauditmanagement.IamWorkSystemDetailWrapper;
//import com.plian.system.wrapper.fr.internalauditmanagement.IamWorkSystemWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.BeanUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * 审计整改-目标清单(IamRectifyTargetList)表服务实现类
// *
// * @author jiatp
// * @since 2023-03-02 14:10:14
// */
//@Service
//@Slf4j
//@AllArgsConstructor
//public class IamWorkSystemServiceImpl extends BaseServiceImpl<IamWorkSystemMapper, IamWorkSystem> implements IamWorkSystemService, BaseFlowService {
//
//
//    private IFormCodeService formCodeService;
//    private final IamWorkSystemWrapper systemWrapper;
//    private final IOrgService orgService;
//    private final IamWorkSystemDetailService systemDetailService;
//    private final IamWorkSystemDetailMapper systemDetailMapper;
//    private final IamWorkSystemDetailWrapper systemDetailWrapper;
//    private FileService fileService;
//
//    private FormWorkflowService formWorkflowService;
//
//    private ISysUserService userService;
//    private ISznbAuditWorkSystemService ythAuditWorkSystemService;
//
//
//    @Override
//    @Transactional(rollbackFor = Throwable.class)
//    public boolean submit(IamWorkSystemVO workSystemVO) {
//        try {
//            IamWorkSystem iamWorkSystem = systemWrapper.voToEntity(workSystemVO);
//            Org org = orgService.getById(iamWorkSystem.getEnterpriseId());
//            if (iamWorkSystem.getId() == null) {
//                iamWorkSystem.setEnterpriseId(Objects.isNull(org)?null:org.getId());
//                iamWorkSystem.setEnterpriseName(Objects.isNull(org)?null:org.getName());
//                iamWorkSystem.setFillingTime(DateUtil.format(new Date(), DateUtil.PATTERN_MONTH));
//                iamWorkSystem.setCode(formCodeService.getCode(FormTypeConstant.IAM_WORK_SYSTEM));
//                iamWorkSystem.setFormType(String.valueOf(FormTypeConstant.IAM_WORK_SYSTEM));
//            }
//            boolean result = super.saveOrUpdate(iamWorkSystem);
//            /**
//             * 制度
//             */
//            List<IamWorkSystemDetailVO> systemDetailList = workSystemVO.getSystemDetailList();
//            if (CollectionUtil.isNotEmpty(systemDetailList)) {
//                systemDetailList.forEach(item -> {
//                    boolean flag = false;
//                    item.setAuditId(iamWorkSystem.getId());
//                    item.setEnterpriseId(iamWorkSystem.getEnterpriseId());
//                    item.setEnterpriseName(iamWorkSystem.getEnterpriseName());
//                    item.setInstitutionName(iamWorkSystem.getInstitutionName());
//                    if (item.getId() == null) {
//                        flag = true;
//                        item.setCode(formCodeService.getCode(FormTypeConstant.IAM_WORK_SYSTEM));
//                        item.setFormType(String.valueOf(FormTypeConstant.IAM_WORK_SYSTEM));
//                        systemDetailService.save(item);
//                    } else {
//                        systemDetailService.updateById(item);
//                    }
//                    if (flag) {
//                        fileService.saveAll(String.valueOf(item.getId()), item.getDocList());
//                    } else {
//                        fileService.edit(String.valueOf(item.getId()), item.getDocList());
//                    }
//                });
//            }
//
//            return true;
//        } catch (Exception e) {
//            log.error("error-submit:" + e.getMessage());
//            throw new MyRuntimeException(new ObjResult("操作失败"));
//        }
//    }
//
//    @Override
//    public IamWorkSystemDTO detail(IamWorkSystem workSystem) {
//        IamWorkSystem iamWorkSystem = getById(workSystem.getId());
//        IamWorkSystemDTO systemDTO = null;
//        if (iamWorkSystem != null) {
//            systemDTO = systemWrapper.entityToDto(iamWorkSystem);
//            List<IamWorkSystemDetail> iamWorkSystemDetails = systemDetailMapper.selectList(new LambdaQueryWrapper<IamWorkSystemDetail>()
//                    .eq(IamWorkSystemDetail::getAuditId, workSystem.getId()));
//            if (CollectionUtil.isNotEmpty(iamWorkSystemDetails)) {
//                List<IamWorkSystemDetailDTO> iamWorkSystemDetailDTOS = systemDetailWrapper.entityToDto(iamWorkSystemDetails);
//                systemDTO.setSystemDetailList(iamWorkSystemDetailDTOS);
//            }
//        }
//        return systemDTO;
//    }
//
//    @Override
//    public ListResult<IamWorkSystemDetailVO> listPage(Query query) {
//        List<SearchEntity> entityList = query.getSearch();
//        if (query.getAscs() == null && query.getDescs() == null) {
//            query.setDescs("create_time");
//        }
//        QueryWrapper<IamWorkSystemDetail> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                Condition.getQueryWrapper(new IamWorkSystemDetail()), entityList
//        );
//        TokenSearch<IamWorkSystemDetail> tokenSearch = new TokenSearch<>();
//		tokenSearch.addTokenQuery(queryWrapper, query);
//        IPage<IamWorkSystemDetail> pages = systemDetailService.page(Condition.getPage(query), queryWrapper);
//        ListResult<IamWorkSystemDetailVO> listResult = new ListResult<>(CommonCode.SUCCESS);
//        List<IamWorkSystemDetail> records = pages.getRecords();
//        List<IamWorkSystemDetailVO> iamWorkSystemDetailVOS = systemDetailWrapper.entityToVO(records);
//        List<IamWorkSystemDetailVO> detailVOList = filterData(iamWorkSystemDetailVOS);
//        listResult.setList(detailVOList);
//        listResult.setTotal(detailVOList.size());
//        return listResult;
//    }
//
//    /**
//     * 将多个制度进行筛选打卡
//     *
//     * @param list
//     * @return
//     */
//    private List<IamWorkSystemDetailVO> filterData(List<IamWorkSystemDetailVO> list) {
//        List<IamWorkSystemDetailVO> detailVOList = new ArrayList<>();
//
//        Map<Long, List<IamWorkSystemDetailVO>> systemDetailVOMap = list.stream()
//                .collect(Collectors.groupingBy(IamWorkSystemDetailVO::getAuditId));
//
//        systemDetailVOMap.forEach((k, v) -> {
//            IamWorkSystemDetailVO detailVO = new IamWorkSystemDetailVO();
//            List<String> sysNameList = v.stream().map(IamWorkSystemDetailVO::getInstitutionSystemName).collect(Collectors.toList());
//            BeanUtils.copyProperties(v.get(0), detailVO);
//            detailVO.setInstitutionSystemName(StringUtils.join(sysNameList, ","));
//            detailVOList.add(detailVO);
//        });
//        return detailVOList;
//    }
//
//    @Override
//    public List<IamWorkSystemVO> getAllSystems(List<IamWorkSystemVO> records) {
//        records.forEach(item -> {
//            List<IamWorkSystemDetail> systemDetailList = systemDetailMapper.selectList(new LambdaQueryWrapper<IamWorkSystemDetail>()
//                    .eq(IamWorkSystemDetail::getAuditId, item.getId()));
//            if (CollectionUtil.isNotEmpty(systemDetailList)) {
//                List<String> sysNameList = systemDetailList.stream().map(e -> e.getInstitutionSystemName()).collect(Collectors.toList());
//                item.setInstitutionSystemName(StringUtils.join(sysNameList, ","));
//            }
//        });
//        return records;
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            IamWorkSystem workSystem = getById(id);
//            if (workSystem == null) {
//                return false;
//            } else if (workSystem.getStatus() != null &&
//                    (workSystem.getStatus() != FormStatusConstant.STASH && workSystem.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//        boolean result = super.deleteLogic(ids);
//        //详情
//        systemDetailService.deleteByParentId(ids);
//        return result;
//    }
//
//    @Override
//    public List<IamWorkSystemDetail> findSystemDetailByEnterId(IamWorkSystemDetailVO workSystemVO) {
//        String enterpriseId = workSystemVO.getEnterpriseId();
//        if (StringUtil.isEmpty(enterpriseId)) {
//            return null;
//        }
//        List<IamWorkSystemDetail> systemDetailList = systemDetailMapper.selectList(new LambdaQueryWrapper<IamWorkSystemDetail>()
//                .eq(IamWorkSystemDetail::getEnterpriseId, enterpriseId));
//        return systemDetailList;
//    }
//
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id           主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            IamWorkSystem workSystem = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH) {
//                workSystem.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                workSystem.setApprovedTime(now);
//            }
//            workSystem.setStatus(updateStatus);
//            updateById(workSystem);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    public HashMap<String, Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String, Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//
//        QueryWrapper<IamWorkSystem> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id", Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<IamWorkSystem> systemList = list(queryWrapper);
//        List<IamWorkSystemVO> workSystemVOList = systemWrapper.entityToVO(systemList);
//        List<PageData> pageDataList = new ArrayList<>();
//        try {
//            if (CollectionUtil.isNotEmpty(workSystemVOList)) {
//                for (IamWorkSystemVO vo : workSystemVOList) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getEnterpriseName());
//                    pd.put("APPLICANTNAME", vo.getCreateUser());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getEnterpriseId());
//                    pd.put("formType", FormTypeConstant.DP_DISCIPLINARY_PERSONNEL_FORM);
//                    pd.put("orgName", vo.getEnterpriseName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.IAM_WORK_SYSTEM);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED);
//    }
//
//
//    @Override
//    @YthTaskObserver
//    public boolean saveWorkSystemByDataSource(String date) {
//
//        boolean flag = true;
//        Date start = DateUtil.parse(date, DateUtil.PATTERN_DATE);
//        //获取数据
//        //List<IamWorkSystemVO> syncDatas = ythAuditWorkSystemService.getSyncData(start, DateUtil.plusDays(start, 1));
//        List<IamWorkSystemVO> syncDatas = ythAuditWorkSystemService.getSyncData(null, null);
//
//        Map<String, String> orgSourceIds = orgService.getSourceId();
//        Map<String, String> userSourceIds = userService.getSourceId();
//
//        if (CollectionUtil.isNotEmpty(syncDatas)) {
//
//            for (IamWorkSystemVO syncData : syncDatas) {
//                //企业
//                String enterpriseId = orgSourceIds.get(syncData.getEnterpriseId());
//                if (StringUtils.isNotBlank(enterpriseId)) {
//                    syncData.setEnterpriseId(enterpriseId);
//                    syncData.setCreateCompanyId(enterpriseId);
//                }
//                //详情数据
//                List<IamWorkSystemDetailVO> systemDetailList = syncData.getSystemDetailList();
//
//                if (CollectionUtil.isNotEmpty(systemDetailList)) {
//                    //查询数据库存在的旧数据
//                    List<IamWorkSystemDetail> oldSystemDetails = systemDetailService.list(new LambdaQueryWrapper<IamWorkSystemDetail>()
//                            .eq(IamWorkSystemDetail::getDataSource, 3)
//                            .in(IamWorkSystemDetail::getDataSourceId, systemDetailList.stream().map(IamWorkSystemDetail::getDataSourceId).collect(Collectors.toList())));
//
//
//                    //删除旧的主表数据和详细数据
//                    if (CollectionUtil.isNotEmpty(oldSystemDetails)) {
//                        List<Long> ids = oldSystemDetails.stream().map(IamWorkSystemDetail::getAuditId).collect(Collectors.toList());
//                        //主表
//                        super.deleteLogic(ids);
//                        //详情
//                        systemDetailService.deleteByParentId(ids);
//                    }
//                    systemDetailList.forEach(detail -> {
//                        detail.setEnterpriseId(enterpriseId);
//                        detail.setCreateCompanyId(enterpriseId);
//                    });
//                    flag = submit(syncData);
//                }
//            }
//        }
//        return flag;
//    }
//}
//
